#pragma once

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <functional>
#include <memory>
#include "ThreadPool.hpp"
#include "Log.hpp"
#include "Common.hpp"
#include "Socket.hpp"
#include "InetAddr.hpp"

using namespace Net_Work;
const static int default_backlog = 6;
using task_t = std::function<void()>;                      // 将IO操作封装成为一个任务，让线程去完成
using Handler_t = std::function<std::string(std::string)>; // 处理任务

class TcpServer
{
private:
    void ProcessConnection(std::shared_ptr<Socket> sock, InetAddr addr)
    {
        std::string request_str;
        if (sock->Recv(&request_str, 4096))
        {
            std::string response = _handler(request_str);
            sock->Send(response);
            sock->CloseSocket();
        }
    }
public:
    TcpServer(uint16_t port, Handler_t handler)
        : _port(port), _handler(handler), _isRunning(false), _listenSock(new TcpSocket())
    {
    }

    // 初始化
    void Init()
    {
        _listenSock->BuildListenSocketMethod(_port, default_backlog);
    }

    void Start()
    {
        _isRunning = true;
        while (_isRunning)
        {
            std::string clientIP;
            uint16_t clientPort;
            std::shared_ptr<Socket> sock = _listenSock->AcceptConnection(&clientIP, &clientPort);
            if (sock == nullptr)
            {
                continue;
            }
            InetAddr clientAddr(clientIP, clientPort);
            task_t task = std::bind(&TcpServer::ProcessConnection, this, sock, clientAddr);
            ThreadPool<task_t>::GetInstance()->Push(task);
        }
        _isRunning = false;
    }

    ~TcpServer()
    {
    }

private:
    uint16_t _port; // 绑定的端口号
    std::unique_ptr<Socket> _listenSock;
    bool _isRunning;
    Handler_t _handler;
};